﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

    public class BytesConverter
    {
        public static byte[] GetBytes(byte value)
        {
            return new byte[] { value };
        }
        public static byte[] GetBytes(bool value)
        {
            return BitConverter.GetBytes(value);
        }
        public static byte[] GetBytes(int value)
        {
            return BitConverter.GetBytes(value);
        }
        public static byte[] GetBytes(short value)
        {
            return BitConverter.GetBytes(value);
        }
        public static byte[] GetBytes(double value)
        {
            return BitConverter.GetBytes(value);
        }
        public static byte[] GetBytes(string value, bool saveLen = false)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(value);
            if (saveLen)
                return GetBytes(buffer.Length).Concat(buffer).ToArray();
            else
                return buffer;
        }
        public static byte[] GetBytes(DateTime value)
        {
            return GetBytes(value.Ticks);
        }
        public static byte[] GetBytes(float value)
        {
            return BitConverter.GetBytes(value);
        }
        public static byte[] GetBytes(long value)
        {
            return BitConverter.GetBytes(value);
        }
        public static bool BytesToBool(byte b)
        {
            return BytesToBool(new byte[] { b });
        }
        public static bool BytesToBool(byte[] b, int index = 0)
        {
            return BitConverter.ToBoolean(b, index);
        }
        public static int BytesToInt(byte[] b, int index = 0)
        {
            return BitConverter.ToInt32(b, index);
        }
        public static short BytesToShort(byte[] b, int index = 0)
        {
            return BitConverter.ToInt16(b, index);
        }
        public static double BytesToDouble(byte[] b, int index = 0)
        {
            return BitConverter.ToDouble(b, index);
        }
        public static string BytesToString(byte[] b)
        {
            return Encoding.UTF8.GetString(b);
        }
        //count:-1时，从b中读取长度
        public static string BytesToString(byte[] b, int index, int count = -1)
        {
            if (count == -1)
                return Encoding.UTF8.GetString(b, index + 4, BytesToInt(b, index));
            else 
                return Encoding.UTF8.GetString(b, index, count);
        }
        public static DateTime BytesToDateTime(byte[] b, int index)
        {
            return new DateTime(BytesToLong(b, index));
        }
        public static float BytesToFloat(byte[] b, int index = 0)
        {
            return BitConverter.ToSingle(b, index);
        }
        public static long BytesToLong(byte[] b, int index = 0)
        {
            return BitConverter.ToInt64(b, index);
        }
    }
